<?php
namespace app\index\controller;

use app\common\model\User as UserModel;
use app\common\model\Fruit as FruitModel;
use app\common\model\FruitFirstLog as FruitFirstLogModel;
use app\common\model\SeedingFirst as SeedingFirstModel;

use app\common\component\seed\SeedService;
use app\common\component\fruit\FruitService;
use app\common\component\fruit\FruitFirstLogService;

class FruitFriends extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$userSelect = UserModel::where('promotion_id', \think\Session::get('user_id')) -> select();

		$users = [];
    	foreach($userSelect as $user) {
    		$users[] = $user;

    		$userSelectC = UserModel::where('promotion_id', $user['user_id']) -> select();
    		if(isset($userSelectC) && !empty($userSelectC)) {
    			foreach($userSelectC as $userc) {
    				$users[] = $userc;

    				$userSelectCC = UserModel::where('promotion_id', $userc['user_id']) -> select();
    				if(isset($userSelectCC) && !empty($userSelectCC)) {
    					foreach($userSelectCC as $usercc) {
    						$users[] = $usercc;
    					}
    				}
    			}
    		}
    	}

    	$this -> view -> assign('users', $users);

        return $this -> view -> fetch();
    }

    public function seedingFirst() {
    	$userId = $this -> request -> get('user_id');

		(new \app\common\component\seeding\SeedingFirstService()) -> getProfit($userId);

		$this -> view -> assign('user', UserModel::get(['user_id' => $userId]));

		$fruitServiceFind = (new FruitService()) -> find($userId);
		if(isset($fruitServiceFind['data']['fruit']['fruit_first'])) {
			$this -> view -> assign('fruitFirst', $fruitServiceFind['data']['fruit']['fruit_first']);
		} else {
			$this -> view -> assign('fruitFirst', 0);
		}

		$seedServiceFind = (new SeedService()) -> find($userId);
		if(isset($seedServiceFind['data']['seed']['seed_first'])) {
			$this -> view -> assign('seedFirst', $seedServiceFind['data']['seed']['seed_first']);
		} else {
			$this -> view -> assign('seedFirst', 0);
		}

		$selectSeeding = SeedingFirstModel::where('user_id = ' . $userId . ' AND status in(3, 4)') -> select();
		$seedings = [];
		foreach($selectSeeding as $seeding) {
			$seedings[$seeding['sort']] = $seeding;
		}

		$this -> view -> assign('seedings', $seedings);

        return $this -> view -> fetch();
    }

	public function getSeedingFirst() {
		$post = $this -> request -> post();
		$currentUserId = \think\Session::get('user_id');

		$strCache = 'getSeedingFirst' . $currentUserId;
		$getUserSeedingFirst = \think\Cache::get($strCache);
		if(isset($getUserSeedingFirst) && isset($getUserSeedingFirst[$post['user_id']])) {
			if($getUserSeedingFirst[$post['user_id']]['get_seeding_first_last_time'] > strtotime('00:00')) {
				return [ 'code' => -1, 'message' => '今天您已经采摘此用户果子!' ];
			}
		} else {
			$getUserSeedingFirst = [];
		}

		//$seedingFirstModelGet = SeedingFirstModel::where('user_id = ' . $post['user_id'] . ' AND status in(3, 4)') -> select();
		$seedingFirstModelGet = SeedingFirstModel::where('user_id = ' . $post['user_id'] . ' AND status = 4') -> select();
		if(!$seedingFirstModelGet || empty($seedingFirstModelGet)) {
			return [ 'code' => -1, 'message' => '没有可采摘的果子!' ];
		}

		$getFruitUser = UserModel::get(['user_id' => $post['user_id']]);

		$currentUserName = \think\Session::get('user_name');
		$currentTime = time();
		$getFruitRand = crypto_rand(1, 10);
		$getFruitNum = 0;

		foreach($seedingFirstModelGet as $seedingFirstModel) {
			if($getFruitRand <= 0) {
				break;
			}

			if($seedingFirstModel -> profit > 0) {
				if($seedingFirstModel -> profit >= $getFruitRand) {
					$seedingFirstModel -> profit -= $getFruitRand;
					$getFruitNum += $getFruitRand;
					$getFruitRand = 0;
				} else {
					$getFruitRand -= $seedingFirstModel -> profit;
					$getFruitNum += $seedingFirstModel -> profit;;
					$seedingFirstModel -> profit = 0;
				}

				\think\Db::startTrans();
				try {
					if(!$seedingFirstModel -> save()) {
						throw new \Exception('采摘果子失败, save');
					}

					if(!FruitModel::where('user_id', $currentUserId) -> setInc('fruit_first', $getFruitNum)) {
						throw new \Exception('采摘果子失败, fruit setInc!');
					}

					$fruitFirstLogServiceCreate = (new FruitFirstLogService()) -> create([
						'user_id' => $currentUserId,
						'type' => 3,
						'active' => 1,
						'price' => $getFruitNum,
						'create_time' => $currentTime,
						'remark' => '采摘[' . $getFruitUser['username'] . ']第' . $seedingFirstModel -> sort . '地的果子'
					]);
					if($fruitFirstLogServiceCreate['code'] != 0) {
						throw new \Exception($fruitFirstLogServiceCreate['message']);
					}

					$fruitFirstLogServiceCreate2 = (new FruitFirstLogService()) -> create([
						'user_id' => $seedingFirstModel -> user_id,
						'type' => 3,
						'active' => 0,
						'price' => $getFruitNum,
						'create_time' => $currentTime,
						'remark' => '被采摘[' . $currentUserName . ']第' . $seedingFirstModel -> sort . '地的果子'
					]);
					if($fruitFirstLogServiceCreate2['code'] != 0) {
						throw new \Exception($fruitFirstLogServiceCreate2['message']);
					}

					$getUserSeedingFirst[$post['user_id']]['get_seeding_first_last_time'] = $currentTime;
					\think\Cache::set($strCache, $getUserSeedingFirst);

					\think\Db::commit();
				} catch(\Exception $e) {
					\think\Db::rollback();

					return ['code' => -1, 'message' => $e -> getMessage()];
				}

			}
		}

		return ['code' => 0, 'message' => '成功采摘了' . $getFruitNum . '个果子'];
	}
}
?>